import React, { useEffect, useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, message, Upload } from 'antd';

interface Props {
    onChange?: (info: string) => void;
    value?: string;
}

const UploadComponnet = (props: Props) => {
    const { onChange, value } = props;
    const [fileList, setFileList] = useState<any[]>(value ? [value] : []);

    useEffect(() => {
        if (value) {
            setFileList([{ "name": value, "url": value }]);
        }
    }, [value]);

    const uploadProps: UploadProps = {
        name: 'file',
        action: import.meta.env.VITE_LLM_API_URL + '/upload',
        maxCount: 1,
        fileList: fileList,
        headers: {
            authorization: 'authorization',
        },
        onChange(info) {
            let newFileList = [...info.fileList].slice(-1); // 只保留最新的一个文件
            setFileList(newFileList);
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                onChange(info.file.response.data)
                message.success(`上传成功过`);
            } else if (info.file.status === 'error') {
                message.error(`上传失败`);
            }
        },
    };

    return <Upload {...uploadProps} >
        <Button icon={<UploadOutlined />}>上传数据集</Button>
    </Upload>
};

export default UploadComponnet;